package com.zjmiec.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.zjmiec.config.OSSProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class aliOSSUtil {
    /**
     * log日志
     */
    public static final Logger logger = LoggerFactory.getLogger(aliOSSUtil.class);
    private static final String endpoint = OSSProperties.ALIYUN_ENDPOINT;
    private static final String accessKeyId = OSSProperties.ALIYUN_ACCESS_ID;
    private static final String accessKeySecret = OSSProperties.ALIYUN_ACCESS_KEY;
    private static final String bucketName = OSSProperties.ALIYUN_BUCKET;
    /**
     * 获取oss
     */
    public static OSS getOSSClient() {
        return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }
    //查找字符串中超链接的地址
    public static List<String> getUrls(String str) {
        Pattern pattern = Pattern.compile("(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]");
        Matcher matcher = pattern.matcher(str);
        List<String> urlArr = new ArrayList<>();
        while (matcher.find()) {
            urlArr.add(matcher.group());
        }
        return urlArr;
    }

    public static String uploadFile(String fileName,String saveFileName) throws FileNotFoundException {
        // 创建OSSClient实例。
        OSS ossClient = getOSSClient();
        // 上传文件流。
        InputStream inputStream = new FileInputStream(fileName);
        ossClient.putObject(bucketName, saveFileName, inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();
        // 获取url地址
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        String url = ossClient.generatePresignedUrl(bucketName, saveFileName, expiration).toString();
        return url;
    }
}